package com.example.library.service;

import com.example.library.entity.Book;
import com.example.library.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BookService {

    @Autowired
    private BookRepository bookRepository;

    @Transactional
    public Book borrowBook(Long bookId) {
        Book book = bookRepository.findBookForUpdate(bookId);
        if (book.getStock() > 0) {
            book.setStock(book.getStock() - 1);
            return bookRepository.save(book);
        } else {
            throw new RuntimeException("Book is out of stock");
        }
    }

    @Transactional
    public void returnBook(Long bookId) {
        Book book = bookRepository.findBookForUpdate(bookId);
        book.setStock(book.getStock() + 1);
        bookRepository.save(book);
    }

    public List<Book> searchBooks(String query) {
        return bookRepository.findByTitleContainingOrIsbnContaining(query, query);
    }

    public List<Book> getAllBooks() {
        return bookRepository.findAll();
    }

    public Book createBook(Book book) {
        return bookRepository.save(book);
    }
}